package com.th.supcom.pds.phamapply.client.page;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.carefx.framework.container.client.page.IPageEntryPoint;
import net.carefx.framework.container.client.page.PageContext;
import net.carefx.framework.reflection.shared.annotations.Reflectable;

import com.extjs.gxt.ui.client.Style.HideMode;
import com.extjs.gxt.ui.client.Style.LayoutRegion;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.util.Margins;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.TabItem;
import com.extjs.gxt.ui.client.widget.TabPanel;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.layout.BorderLayout;
import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.th.supcom.pds.common.client.model.CodeConstants;
import com.th.supcom.pds.common.utils.ClientUtils;
import com.th.supcom.pds.phamapply.client.model.InpPhamApplyDetailSummaryModel;
import com.th.supcom.pds.phamapply.client.model.InpPhamDispenseDetailModel;
import com.th.supcom.pds.phamapply.client.service.InpPhamDispenseDetailRpc;
import com.th.supcom.pds.phamapply.client.service.InpPhamDispenseDetailRpcAsync;
import com.th.supcom.pds.phamapply.client.widget.checkdispense.InpCheckDispenseCollectGrid;
import com.th.supcom.pds.phamapply.client.widget.checkdispense.InpCheckDispenseDetailGrid;
import com.th.supcom.pds.phamapply.client.widget.phamapplydetail.InpPhamApplySearchPanel;

/**
 *药房摆药查询入口类实现.
 * 
 */
@Reflectable
public class InpCheckDispenseQueryEntryPoint implements IPageEntryPoint
{
    private InpPhamApplySearchPanel m_inpPhamApplySearchPanel;
    private InpCheckDispenseDetailGrid m_inpCheckDispenseDetailGrid;
    private InpCheckDispenseCollectGrid m_inpCheckDisenpseCollectGrid;
    private static InpPhamDispenseDetailRpcAsync s_dipenseDetailRpc = GWT.create (InpPhamDispenseDetailRpc.class);
    @Override
    public void start (PageContext context)
    {
        context.getWorkBench ().getBodyView ().getWorkspace ().getContextView ().asLayoutContainer ().hide ();
        LayoutContainer mainLayoutContainer;
        mainLayoutContainer = context.getContainer ();
        mainLayoutContainer.setLayout (new BorderLayout ());
        mainLayoutContainer.setHideMode (HideMode.OFFSETS);
        
        m_inpPhamApplySearchPanel = new InpPhamApplySearchPanel ("摆药查询");
        m_inpCheckDispenseDetailGrid=new InpCheckDispenseDetailGrid();
        ColumnModel columnModel=m_inpCheckDispenseDetailGrid.getColumnModel ();
        ColumnConfig column = null;
        column = new ColumnConfig ("dispenseIndicatorName", "摆药状态", 100);
        columnModel.getColumns ().add (column);
        m_inpCheckDisenpseCollectGrid=new InpCheckDispenseCollectGrid();
                
        TabPanel tabPanel = new TabPanel ();
        tabPanel.setLayoutData (new FitLayout ());

        TabItem detailItem = new TabItem ("摆药明细");
        detailItem.add (m_inpCheckDispenseDetailGrid);
        detailItem.setLayout (new FitLayout ());
        TabItem collectItem = new TabItem ("摆药汇总");
        collectItem.add (m_inpCheckDisenpseCollectGrid);
        collectItem.setLayout (new FitLayout ());

        tabPanel.add (detailItem);
        tabPanel.add (collectItem);
        
        BorderLayoutData centerData = new BorderLayoutData (LayoutRegion.CENTER);
        centerData.setMargins (new Margins (2, 0, 2, 0));
        BorderLayoutData northData = new BorderLayoutData (LayoutRegion.NORTH, 50);
        northData.setMargins (new Margins (2, 5, 2, 0));

        mainLayoutContainer.add (tabPanel, centerData);
        mainLayoutContainer.add (m_inpPhamApplySearchPanel, northData);
        
        addEventListeners ();
    }

    @Override
    public void stop (PageContext context)
    {
        return;
    }
    /**
     * 添加组事件
     */
    private void addEventListeners ()
    {

        m_inpPhamApplySearchPanel.getQueryBtn ().addSelectionListener (new SelectionListener <ButtonEvent> ()
        {

            @Override
            public void componentSelected (final ButtonEvent ce)
            {
                loadData ();
            }
        });
        m_inpPhamApplySearchPanel.getClearBtn ().addSelectionListener (new SelectionListener <ButtonEvent> ()
        {
            @Override
            public void componentSelected (final ButtonEvent ce)
            {
                clearData ();
            }

        });

    }
    private void loadData ()
    {
        if(!veryParams ()){
            return;
        };
        m_inpCheckDispenseDetailGrid.getGrid ().mask ("正在拼命加载中");
        InpPhamDispenseDetailModel inpPhamDispenseDetail=new InpPhamDispenseDetailModel();
        inpPhamDispenseDetail.setDispenseIndicator (m_inpPhamApplySearchPanel.getDispenseIndicator ().getValue ().getDispenseIndicator ());
        inpPhamDispenseDetail.setStartTime (m_inpPhamApplySearchPanel.getBeginDate ().getValue ());
        inpPhamDispenseDetail.setEndTime (m_inpPhamApplySearchPanel.getEndDate ().getValue ());
        inpPhamDispenseDetail.setPerformDispensary (ClientUtils.getOrgModel().getOrgCode());
        //inpPhamDispenseDetail.setNurseUnit (ClientUtils.getOrgModel().getOrgCode());
        s_dipenseDetailRpc.getInpCheckDispenseDetail (inpPhamDispenseDetail,
                                                      new AsyncCallback <List <InpPhamDispenseDetailModel>> ()
                                                      {

                                                          @Override
                                                          public void onFailure (Throwable caught)
                                                          {
                                                              m_inpCheckDispenseDetailGrid.getGrid ().unmask ();
                                                              MessageBox.alert (CodeConstants.PROMPT, caught.getLocalizedMessage (), null);
                                                          }

                                                          @Override
                                                          public void onSuccess (List <InpPhamDispenseDetailModel> result)
                                                          {
                                                              m_inpCheckDispenseDetailGrid.getGrid ().unmask ();
                                                              m_inpCheckDispenseDetailGrid.getStore ().removeAll ();
                                                              m_inpCheckDispenseDetailGrid.getStore ().add (result);
                                                              getPhamApplySummary ();
                                                          }
                                                      });
    }

    private boolean veryParams ()
    {
        if (m_inpPhamApplySearchPanel.getDispenseIndicator ().getValue () == null)
        {
            ClientUtils.alertMessageBox ("请输入请领单据号", m_inpPhamApplySearchPanel.getDispenseIndicator ());
            return false;
        }
        if (m_inpPhamApplySearchPanel.getBeginDate ().getValue ()== null)
        {
            ClientUtils.alertMessageBox ("请选择开始时间", m_inpPhamApplySearchPanel.getBeginDate ());
            return false;
        }
        if (m_inpPhamApplySearchPanel.getEndDate ().getValue () == null)
        {
            ClientUtils.alertMessageBox ("请选择结束时间", m_inpPhamApplySearchPanel.getEndDate ());
            return false;
        }
        if(m_inpPhamApplySearchPanel.getBeginDate ().getValue ().after (m_inpPhamApplySearchPanel.getEndDate ().getValue ())){
            ClientUtils.alertMessageBox ("开始时间大于结束时间", m_inpPhamApplySearchPanel.getBeginDate ());
            return false;
        }
        return true;
    }
    /**清屏*/
    private void clearData ()
    {
        m_inpPhamApplySearchPanel.getDispenseIndicator ().clear ();
        m_inpCheckDispenseDetailGrid.clear ();;
        m_inpCheckDisenpseCollectGrid.clear ();
    }
    /**
     * 获取药品请领汇总
     */
    public void getPhamApplySummary ()
    {
        List <InpPhamDispenseDetailModel> models = m_inpCheckDispenseDetailGrid.getGrid ().getStore ().getModels ();
        List <InpPhamApplyDetailSummaryModel> summaryModels = new ArrayList <InpPhamApplyDetailSummaryModel> ();
        // 按照药品进行分组，计算每个药品的汇总
        Map <String, List <InpPhamDispenseDetailModel>> phamMap = convertToMapByPhamCode (models);
        for (Map.Entry <String, List <InpPhamDispenseDetailModel>> phamEntry : phamMap.entrySet ())
        {
            summaryModels.add (statPham (phamEntry.getValue ()));
        }
        m_inpCheckDisenpseCollectGrid.getGrid ().getStore ().removeAll ();
        m_inpCheckDisenpseCollectGrid.getGrid ().getStore ().add (summaryModels);
    }
    /**
     * 根据药品标准码将list转换成Map
     * @return
     */
    private Map <String, List <InpPhamDispenseDetailModel>> convertToMapByPhamCode (List <InpPhamDispenseDetailModel> models)
    {
        Map <String, List <InpPhamDispenseDetailModel>> map = new HashMap <String, List <InpPhamDispenseDetailModel>> ();
        for (InpPhamDispenseDetailModel inpPhamDispenseDetailModel : models)
        {
            List <InpPhamDispenseDetailModel> temp = null;

            if (map.containsKey (inpPhamDispenseDetailModel.getPhamStdCode ()))
            {
                temp = map.get (inpPhamDispenseDetailModel.getPhamStdCode ());
            }
            else
            {
                temp = new ArrayList <InpPhamDispenseDetailModel> ();
            }
            temp.add (inpPhamDispenseDetailModel);
            map.put (inpPhamDispenseDetailModel.getPhamStdCode (), temp);
        }
        return map;
    }
    /**
     * 药品统计
     */
    private InpPhamApplyDetailSummaryModel statPham (List <InpPhamDispenseDetailModel> list)
    {
        InpPhamApplyDetailSummaryModel summaryModel = new InpPhamApplyDetailSummaryModel ();

        int applyCountSum = 0;
        double costSum = 0.0;
        if (list.isEmpty ())
        {
            return summaryModel;
        }

        for (InpPhamDispenseDetailModel model : list)
        {
            if (null == model.getApplyAmount () || null == model.getCosts ())
            {
                continue;
            }
            applyCountSum += model.getApplyAmount ();
            costSum += model.getCosts ();
        }
        InpPhamDispenseDetailModel detailModel = list.get (0);

        summaryModel.setDetailSumAmount (applyCountSum);
        summaryModel.setPhamStdCode (detailModel.getPhamStdCode ());
        summaryModel.setDispensary (detailModel.getPerformDispensary ());
        summaryModel.setDispensaryName (detailModel.getPerformDispensaryName ());
        summaryModel.setPhamName (detailModel.getPhamName ());
        summaryModel.setPhamSpec (detailModel.getPhamSpec ());
        summaryModel.setTotalCost (costSum);
        summaryModel.setDosageUnit (detailModel.getDispenseUnitName ());
        getDetailInfo (list, summaryModel);
        return summaryModel;
    }
    private void getDetailInfo (List <InpPhamDispenseDetailModel> list, InpPhamApplyDetailSummaryModel summaryModel)
    {
        // 记录每个药品,每个人的药品申请数量、实际摆药数量、冲抵数量
        Map <Long, Map <String, Integer>> countMap = new HashMap <Long, Map <String, Integer>> ();
        // 记录每个人的患者信息
        Map <Long, InpPhamDispenseDetailModel> patInfoMap = new HashMap <Long, InpPhamDispenseDetailModel> ();
        for (InpPhamDispenseDetailModel model : list)
        {
            // 申请数量
            int applyCount = 0;
            // 实际摆药数量
            int actualCount = 0;
            // 冲抵数量
            int offsetCount = 0;
            // 记录单个药品的申请数量、实际摆药数量、冲抵数量
            Map <String, Integer> map = null;

            if (countMap.containsKey (model.getPaiVisitId ()))
            {
                map = countMap.get (model.getPaiVisitId ());
            }
            else
            {
                map = new HashMap <String, Integer> ();
            }

            if (map.containsKey ("applyCount"))
            {
                applyCount = map.get ("applyCount");
            }

            if (map.containsKey ("actualCount"))
            {
                actualCount = map.get ("actualCount");
            }

            if (map.containsKey ("offsetCount"))
            {
                offsetCount = map.get ("offsetCount");
            }

            applyCount += model.getApplyAmount ();
            if (null != model.getDispenseAmount ())
            {
                actualCount += model.getDispenseAmount ();
                offsetCount += model.getApplyAmount () - model.getDispenseAmount ();
            }
            map.put ("applyCount", applyCount);
            map.put ("actualCount", actualCount);
            map.put ("offsetCount", offsetCount);
            countMap.put (model.getPaiVisitId (), map);
            patInfoMap.put (model.getPaiVisitId (), model);
        }
        // 摆药明细
        String dispenseInstr = "";
        // 冲抵明细
        String offsetInStr = "";
        // 实际摆药总量
        int actualDispeseCount = 0;
        int offsetAmount = 0;
        for (Map.Entry <Long, Map <String, Integer>> entry : countMap.entrySet ())
        {
            dispenseInstr += patInfoMap.get (entry.getKey ()).getBedNo () + "&" + countMap.get (entry.getKey ()).get ("applyCount") + " ";
            if (countMap.get (entry.getKey ()).get ("offsetCount") > 0)
            {
                offsetInStr += patInfoMap.get (entry.getKey ()).getBedNo () + "&" + countMap.get (entry.getKey ()).get ("offsetCount") + " ";
            }
            actualDispeseCount += countMap.get (entry.getKey ()).get ("actualCount");
            offsetAmount += countMap.get (entry.getKey ()).get ("offsetCount");
        }
        summaryModel.set ("offsetAmount", offsetAmount);
        summaryModel.set ("dispenseInstr", dispenseInstr);
        summaryModel.set ("offsetInStr", offsetInStr);
        summaryModel.set ("actualDispeseCount", actualDispeseCount);
    }
    /** 提交路径. */
    public static final String SCC_BRANCH = "$URL$";

    /** 提交日期. */
    public static final String SCC_LAST_MODIFICATION_DATE = "$Date$";

    /** 最终修改人员. */
    public static final String SCC_LAST_MODIFIER_NAME = "$Author$";

    /** 最终版本号. */
    public static final String SCC_REVISION = "$Revision$";
}